package dai.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class UITweenModel : ViewModel() {
    var frameCount = 0
    val tweenManager: UITweenManager = UITweenManager()
    var running = true
    var lastTimeMs = -1L

    fun startLoop() {
        viewModelScope.launch {
            launch(Dispatchers.Default) {
                while (running) {
                    if (lastTimeMs > 0) {
                        val curMs = System.currentTimeMillis()
                        val delta = (curMs - lastTimeMs) / 1000f
                        lastTimeMs = curMs
                        withContext(Dispatchers.Main) {
                            tweenManager.update(delta)
                        }
                        val spend = System.currentTimeMillis() - curMs
                        if (spend < 16L) {
                            delay(16L - spend)
                        }
                    } else {
                        lastTimeMs = System.currentTimeMillis()
                    }
                    frameCount++
                }
            }
        }
    }

    override fun onCleared() {
        running = false
        tweenManager.release()
        super.onCleared()
    }
}